<template>
  <div style="padding:10px">
     <main-layout>
      <div>
        <div class="back-view">
          <div class="title vxe-icon-feedback" >确认订单
          </div>
          <div class="back" @click="onClose">
            <vxe-button  size="small" content="返回" icon="vxe-icon-undo"></vxe-button>
          </div>
        </div>
        <div style="width:100%;position: relative;">
              <el-form label-width="80px" class="show-box">
                <el-form-item label="收货人:" style="margin-bottom: 0;">
                  {{addressInfo.receiverName}}
                </el-form-item>
                <el-form-item label="手机号码:" style="margin-bottom: 0;">
                  {{addressInfo.receiverPhone}}
                </el-form-item>
                <el-form-item label="收货地址:" style="margin-bottom: 0;">
                  {{addressInfo.receiverProvince}}/{{addressInfo.receiverCity}}/{{addressInfo.receiverRegion}}/{{addressInfo.receiverDetailAddress}}
                </el-form-item>
              </el-form>
              <div class="update-address" @click="addFlag=true">更改</div>
            </div>
        <el-form >
          <el-form-item> 
           <div style="width:100%;position: relative;">
                <template v-for="(item,index) in orderList">
                    <div style="font-size:14px;font-weight:bold;color: #565656;margin-top: 10px">{{item.title}}</div>
                      <vxe-table
                        border
                        :span-method="spanMethod"
                        size="small"  
                        :data="item.omsSettleOrderItemVoList">
                        <vxe-column field="label" title="商品图片" width="80">
                          <template #default="{row}">
                            <template v-if="row.pmsSpuImagesVoList && row.pmsSpuImagesVoList.length>0">
                            <imageView style="height:60px;width:60px" :url="row.pmsSpuImagesVoList[0].url" />
                          </template>
                          </template>
                        </vxe-column>
                        <vxe-column field="spuName" title="商品名称"></vxe-column>
                        <vxe-column field="skuName" title="产品规格"></vxe-column>
                        <vxe-column field="salesAmount.standardString" title="价格(元)"></vxe-column> 
                        <vxe-column field="buyQuantity" title="数量" align="center" width="180">
                          <template #default="{row}">
                            <el-input-number v-model="row.buyQuantity" @change="changeNumber" :min="1" :max="row.inventory"></el-input-number>
                          </template>
                        </vxe-column>
                        <vxe-column field="subtotalExecAmount.standardString" title="金额(元)"></vxe-column>
                        <vxe-column field="subtotalCouponAmount.standardString" title="优惠(元)"></vxe-column>
                        <vxe-column field="subtotalYunfeiAmount.standardString" title="运费(元)">
                        </vxe-column>
                      </vxe-table> 
                    <div class="bottom-view">
                        <div  class="left">
                          <div style="padding:10px 0;display: flex; align-items: center;">
                            备注：
                          <el-input
                            style="width:400px;"
                            type="textarea"
                            @change="changeNote(item,index)"
                            :autosize="{minRows:1, maxRows: 4}"
                            placeholder="请输入备注"
                            v-model="item.note">
                          </el-input>
                          </div>
                          
                        </div>
                        <div class="right">
                          <div>货品总金额：<span>{{item.totalAmount?.amount||0}}</span>元</div>
                          <div>运费共计：<span>{{item.totalYunfeiAmount?.amount||0}}</span>元</div>
                        </div>
                    </div>
                 </template>
  
          </div>
          </el-form-item>
          <el-form-item>
            <div class="bottom-view" style="border: none; align-items: self-start;">
                         <div  class="left">
                          总计：货品种类：{{formdata.skuNum}}种 数量总计：{{formdata.totalQuantity}}件
                        </div>
                        <div class="right">
                          <div>货品总金额：<span>{{formdata.totalAmount?.standardString||0}}</span>元</div>
                          <div>优惠共计：<span>{{formdata.totalCouponAmount?.standardString||0}}</span>元</div>
                          <div>运费共计：<span>{{formdata.totalYunfeiAmount?.standardString||0}}</span>元</div>
                          <div>应付金额：<span style="color: #FF9C00;">{{formdata.totalPayAmount?.standardString||0}}</span>元</div>
                        </div>
                    </div>
          </el-form-item>
          <el-form-item>
            <div class="bottom-view" style="border: none; align-items: self-start;">
                         <div  class="left">
                        </div>
                        <div class="right" style="display: flex;">
                          <div style="padding-right:30px">应付总金额：<span style="color: #FF9C00;font-size:18px;">{{formdata.totalPayAmount?.standardString||0}}</span>元</div>
                          <el-button type="primary" @click="onSubmit"><vxe-icon name="check"></vxe-icon> 提交订单</el-button>

                        </div>
                    </div>
          </el-form-item>
      </el-form>
       <addView v-if="addFlag" :show="addFlag" @success="getAddressInfo" @close="addFlag=false" />

       </div>
    </main-layout>
</div> 
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { createOrder,orderSettle} from '@/api/order'
import mainLayout from '@/components/custom/mainLayout.vue'
import imageView from '@/components/custom/image.vue'
import { VXETable } from 'vxe-table'
import { useRouter } from 'vue-router'
import addView from '@/view/set/address/components/add.vue'
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()

const router = useRouter()
const formdata = ref({})
const addFlag = ref(false)
const orderList = ref([])
const saveType = ref(true)
const addressInfo = ref({})

onMounted(async () => { 
  console.log(userStore.userInfo,'========')
  let obj = JSON.parse(localStorage.getItem('set-order-list'))
  if(obj){
    orderList.value =obj.omsSettleOrderVoList ||[]
    formdata.value = obj
    addressInfo.value = obj
  }
})
const spanMethod =   ({ row, _rowIndex, column, visibleData })=>{
        const fields = ['orderId']
        function getValueByData(obj,path) {
          let paths = path.split('.');
          let res = obj;
          let prop;
          while(prop = paths.shift()) {
            if(res[prop]){
                res = res[prop]
            }
          }
          return res;
        }
        if(column.property){
          const cellValue =getValueByData(row,column.property)
          if (cellValue && fields.includes(column.property)) {
            const prevRow = visibleData[_rowIndex - 1]
            let nextRow = visibleData[_rowIndex + 1]
              if (prevRow && getValueByData(prevRow,column.property) === cellValue) {
                return { rowspan: 0, colspan: 0 }
                } else {
                let countRowspan = 1
                while (nextRow && getValueByData(nextRow,column.property)=== cellValue) {
                  nextRow = visibleData[++countRowspan + _rowIndex]
                }
                if (countRowspan > 1) {
                  return { rowspan: countRowspan, colspan: 1 }
                }
              }
          }
        }
}

const changeNote =(item,index)=>{
  sessionStorage.setItem('note-'+index,item.note)
}
const getAddressInfo =(info)=>{
  addressInfo.value = info
}


const onSubmit = async() => {
    if(!saveType.value){return}
      saveType.value=false
      let pdataList =[]
      let notesList =[]
      orderList.value.forEach((list)=>{
        notesList.push({
          note:list.note,
          supplierInfoId:list.omsSettleOrderItemVoList[0]?.supplierInfoId
        })
        list.omsSettleOrderItemVoList.forEach((item)=>{
            pdataList.push({
                  buyQuantity:item.buyQuantity,
                  spuInfoId:item.spuInfoId,
                  skuInfoId:item.skuInfoId,
                  supplierInfoId:item.supplierInfoId||1,
            })
          })
      })
     let res =await createOrder({
          note:formdata.value.note,
          createName:userStore.userInfo.nickName,
          createId:userStore.userInfo.userId,
          companyId:userStore.userInfo.companyId,
          farmId:userStore.userInfo.farmId,
          createPhone:userStore.userInfo.farmList?.find((item)=>item.farmId==userStore.userInfo.farmId).contactsPhone||userStore.userInfo.userName,
          omsOrderItemAddDtoList:pdataList,
          omsOrderNoteAddDtoList:notesList,
          receiverCity:addressInfo.value.receiverCity,
          receiverDetailAddress:addressInfo.value.receiverDetailAddress,
          receiverName:addressInfo.value.receiverName,
          receiverPhone:addressInfo.value.receiverPhone,
          receiverPostCode:addressInfo.value.receiverPostCode,
          receiverProvince:addressInfo.value.receiverProvince,
          receiverRegion:addressInfo.value.receiverRegion
     })
      if (res.success) {
        VXETable.modal.message({ content: '提交订单成功!',status:'success' })
        saveType.value=true
        router.push(`./pay-order`)
      } else {
        saveType.value=true
        VXETable.modal.message({ content: res.message,status:'error'})
      }
}
const changeNumber =async ()=>{
    let pdataList =[]
    orderList.value.forEach((list)=>{
      list.omsSettleOrderItemVoList.forEach((item)=>{
        pdataList.push({
            buyQuantity:item.buyQuantity||1,
            spuInfoId:item.spuInfoId,
            skuInfoId:item.skuInfoId,
            supplierInfoId:item.supplierInfoId||1
        })
      })
    })
    
    let res =await orderSettle({
        note:formdata.textarea,
        createName:userStore.userInfo.nickName,
        createId:userStore.userInfo.userId,
        createPhone:userStore.userInfo.farmList?.find((item)=>item.farmId==userStore.userInfo.farmId).contactsPhone||userStore.userInfo.userName,
        omsOrderItemAddDtoList:pdataList,
        receiverCity:addressInfo.value.receiverCity,
        receiverDetailAddress:addressInfo.value.receiverDetailAddress,
        receiverName:addressInfo.value.receiverName,
        receiverPhone:addressInfo.value.receiverPhone,
        receiverPostCode:addressInfo.value.receiverPostCode,
        receiverProvince:addressInfo.value.receiverProvince,
        receiverRegion:addressInfo.value.receiverRegion
     })
    if(res.success){
      orderList.value =res.data.omsSettleOrderVoList.map((item,index)=>{
        item.note = sessionStorage.getItem('note-'+index)||formdata.textarea
        return item
      }) ||[]
      formdata.value = res.data
    }

}
const onClose = ()=>{
  router.go(-1)
  orderList.value.forEach((item,index)=>{
    sessionStorage.removeItem('note-'+index)
  })
}

</script>
<style lang="scss" scoped>
.show-box{
    width:100%;
    background-color: #fff;
    margin: 10px 0;
    border-radius: 2px;
    padding: 10px 0;
    border:1px solid #e8eaec;
}
.bottom-view{
  width:99.8%;
  border-top:none;
  display: flex;
  justify-content:space-between;
  align-items: center;
  font-size:13px;
  color:#565656;
  padding:0;
  border:1px solid #ddd;
  border-top: none;
  span{
    font-weight: bold;
    font-size:15px;
    padding-right:4px;
  }
  .left{
    padding-left:10px;
  }
  .right{
    padding-right:10px;
  }
}
.back-view{
    display: flex;
    justify-content: space-between;
    padding: 0 10px 15px 0;
    align-items: center;
    border-bottom:1px solid #ddd;
    margin-bottom:20px;
    .title{
      font-size:15px;
      font-weight: bold;
      color:#565656;
      position: relative;  


      text-indent:6px;
    }
    .title::before {
      content: "";
      display: block;
      width: 3px;
      background: #FF9C00;
      height: 16px;
      margin: 0 3px 0 0;
      position: absolute;
      top: 50%;
      margin-top: -9px;
  }
  .back{
    font-size:15px;
    color:#888;
    cursor: pointer;
  }
}
.update-address{
    position: absolute;
    height: 30px;
    width: 60px;
    text-align: center;
    right: 20px;
    top: 50%;
    margin-top: -15px;
    line-height: 30px;
    color: #04AE70;
    cursor: pointer;
}
</style>
